package wang.walkline.remotewol.ui.management;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import wang.walkline.remotewol.DeviceItem;
import wang.walkline.remotewol.DeviceItemAdapter;
import wang.walkline.remotewol.R;

import java.util.ArrayList;
import java.util.List;

public class ManagementFragment extends Fragment {
    private final String TAG = "ManagementFragment";
    private ListView listView;
    private DeviceItemAdapter device_item_adapter;
    private final List<DeviceItem> lists = new ArrayList<>();
    private WifiManager wifiManager;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_management, container, false);
        Button button_searching_devices = root.findViewById(R.id.button_searching_devices);

        device_item_adapter = new DeviceItemAdapter(getActivity(), R.layout.ui_device_item, lists);
        listView = root.findViewById(R.id.device_list_view);
        button_searching_devices.setOnClickListener(v -> search_devices());

        return root;
    }

    private void search_devices() {
        device_item_adapter.clear();
        wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        wifiManager.startScan();

        List<ScanResult> result = wifiManager.getScanResults();

        if (result != null && result.size() > 0) {
            for (ScanResult scanResult : result) {
                if (scanResult.SSID.startsWith("wol_")) {
                    lists.add(new DeviceItem(scanResult.SSID, scanResult.BSSID, R.drawable.ic_dashboard_black_24dp));
                }
            }

            listView.setAdapter(device_item_adapter);
        } else {
            Toast.makeText(getActivity(), "failed", Toast.LENGTH_SHORT).show();
        }

        listView.setOnItemClickListener((parent, view, position, id) -> {
            DeviceItem deviceItem = (DeviceItem) device_item_adapter.getItem(position);
            setup_device(deviceItem.getSSID());
        });
    }

    private void setup_device(String ssid) {
        if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {wifiManager.setWifiEnabled(true);}

        int netID = wifiManager.addNetwork(createWifiConfig(ssid));
        boolean enabled = wifiManager.enableNetwork(netID, true);

        Log.v(TAG,"netID: " + netID + ", enabled: " + enabled);

        if (enabled) {

        }
    }

    private WifiConfiguration createWifiConfig(String ssid) {
        WifiConfiguration config = new WifiConfiguration();

        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        config.hiddenSSID = true;
        config.SSID = "\"" + ssid + "\"";
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        WifiConfiguration lastConfig = isWifiConfigExist(ssid);

        if (lastConfig != null) {wifiManager.removeNetwork(lastConfig.networkId);}

        return  config;
    }

    private WifiConfiguration isWifiConfigExist(String ssid) {
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();

        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\"" + ssid + "\"")) {return config;}
        }

        return null;
    }
}